package com.s10.ecloud.web.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.s10.ecloud.web.dao.IDeviceGroupDAO;
import com.s10.ecloud.web.model.DeviceGroup;
import com.s10.ecloud.web.model.DeviceModel;
import com.s10.ecloud.web.model.PageModel;

@Repository
public class DeviceGroupDAO implements IDeviceGroupDAO {

	@Resource
	private SessionFactory sessionFactory;

	@Override
	public void makeDeviceGroupPageModel(PageModel pageModel, int userID) {
		String queryCountHql = "select count(*) from DeviceGroup where userId=:userID";
		List datas;
		long totoalPages = 0;

		Query query = sessionFactory.getCurrentSession().createQuery(
				queryCountHql);
		query.setParameter("userID", userID);

		totoalPages = ((Long) query.uniqueResult()).longValue();

		queryCountHql = "from DeviceGroup where userId=:userID";

		query = sessionFactory.getCurrentSession().createQuery(queryCountHql);
		query.setParameter("userID", userID);

		datas = query.setFirstResult(pageModel.getOffset())
				.setMaxResults(pageModel.getMaxPageItems()).list();

		pageModel.setTotal((int) totoalPages);
		pageModel.setList(datas);

	}

	@Override
	public DeviceGroup getDeviceGroupById(int id) {
		Object o = sessionFactory.getCurrentSession()
				.get(DeviceGroup.class, id);
		if (o != null)
			return (DeviceGroup) o;
		else
			return null;
	}

	@Override
	public void updateDeviceGroup(DeviceGroup deviceGroup) {
		sessionFactory.getCurrentSession().update(deviceGroup);
	}

	@Override
	public void deleteDeviceGroup(DeviceGroup model) {
		sessionFactory.getCurrentSession().delete(model);
	}

	@Override
	public void addDeviceGroup(DeviceGroup model) {
		sessionFactory.getCurrentSession().save(model);
	}
}
